<template>
  <el-dialog
    :close-on-click-modal="false"
    title="材料采购合同结算明细"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="120px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号" prop="number">
            <el-input
              v-model="form.number"
              :disabled="true"
              placeholder="自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算数量" prop="settleCount">
            <el-input v-model="form.settleCount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算金额" prop="settleAmount">
            <el-input v-model="form.settleAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付日期" prop="payTime">
            <el-date-picker
              v-model="form.payTime"
              :disabled="disableForm"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付方式" prop="payType">
            <el-select
              v-model="form.payType"
              :disabled="disableForm"
              style="width: 100%"
              placeholder="请选择支付方式"
            >
              <el-option
                v-for="item in payTypes"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付单位" prop="payUnit">
            <el-select
              v-model="form.payUnit"
              :disabled="disableForm"
              style="width: 100%"
              placeholder="请选择支付单位"
            >
              <el-option label="公司" :value="1" />
              <el-option label="分公司" :value="2" />
              <el-option label="项目" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          :disabled="disableForm"
        />
      </el-form-item>
    </el-form>
    <div class="btns" style="padding-bottom: 10px">
      <el-button type="primary" @click="addRow">新增行</el-button>
      <el-button type="primary" @click="delRow">删除行</el-button>
    </div>
    <com-table
      v-model="selectRow"
      highlight-current-row
      :data="detailDataList"
      :columns="columns"
      :no-page="true"
    >
      <template v-slot:number="{ row }">
        <el-input v-model="row.number" />
      </template>
      <template v-slot:name="{ row }">
        <el-input v-model="row.name" />
      </template>
      <template v-slot:specification="{ row }">
        <el-input v-model="row.specification" />
      </template>
      <template v-slot:unit="{ row }">
        <el-input v-model="row.unit" />
      </template>
      <template v-slot:taxRate="{row}">
        <el-input v-model="row.taxRate" />
      </template>
      <template v-slot:taxes="{row}">
        <el-input v-model="row.taxes" />
      </template>
      <template v-slot:count="{ row }">
        <el-input v-model="row.count" @input="inputCount" />
      </template>
      <template v-slot:price="{ row }">
        <el-input v-model="row.price" @input="inputPrice" />
      </template>
      <template v-slot:amount="{ row }">
        <el-input v-model="row.amount" />
      </template>
      <template v-slot:description="{ row }">
        <el-input v-model="row.description" />
      </template>
      <template v-slot:createTime="{ row }">
        <el-date-picker v-model="row.createTime" type="date" placeholder="选择日期" />
      </template>
      <template v-slot:settleCount="{ row }">
        <el-input v-model="row.settleCount" @input="inputSettleCount" />
      </template>
      <template v-slot:settleAmount="{ row }">
        <el-input v-model="row.settleAmount" @input="inputSettleAmount" />
      </template>
    </com-table>
    <el-button
      style="margin-top: 10px"
      type="primary"
      @click="showFileModal = true"
    >附件资料({{ fileList.length }})</el-button>
    <file-uploader
      v-model="fileList"
      :show-modal.sync="showFileModal"
      :disabled="disableForm"
      :can-download="optType === 'detail'"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  addMaterialContractSettleInfo,
  updateMaterialContractSettleInfo,
  getMaterialContractSettleInfoDetail,
  getMaterialContractMaterialList
} from '@/api/runManage'
import { payTypes, payUnits } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import moment from 'moment'
export default {
  name: 'AddMaterialContractInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    id: {
      type: String,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    relateData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      selectRow: null,
      detailDataList: [],
      payTypes,
      payUnits,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        number: '',
        settleCount: '',
        settleAmount: '',
        payTime: '',
        payType: '',
        payUnit: '',
        remark: ''
      },
      fileList: [],
      columns: [
        {
          label: '材料编号',
          prop: 'number',
          slot: 'number'
        },
        {
          label: '材料名称',
          slot: 'name',
          prop: 'name'
        },
        {
          label: '规格',
          slot: 'specification',
          prop: 'specification'
        },
        {
          label: '单位',
          slot: 'unit',
          prop: 'unit'
        },
        {
          label: '税率',
          slot: 'taxRate',
          width: '150'
        },
        {
          label: '税金',
          slot: 'taxes',
          width: '150'
        },
        {
          label: '数量',
          prop: 'count',
          slot: 'count',
          width: '150'
        },
        {
          label: '单价',
          prop: 'price',
          slot: 'price',
          width: '150'
        },
        {
          label: '金额',
          prop: 'amount',
          slot: 'amount',
          width: '150'
        },
        {
          label: '结算数量',
          prop: 'settleCount',
          slot: 'settleCount',
          width: '150'
        },
        {
          label: '结算金额',
          prop: 'settleAmount',
          slot: 'settleAmount',
          width: '150'
        },
        {
          label: '描述',
          prop: 'description',
          slot: 'description',
          width: '150'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          slot: 'createTime',
          width: '150'
        }
      ],
      rules: {
        settleCount: [
          { required: true, message: '请输入本次结算金额', trigger: 'change' }
        ],
        settleAmount: [
          { required: true, message: '请输入本次支付金额', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (this.optType === 'add') {
        getMaterialContractMaterialList({
          materialContractInfoId: this.id
        }).then((res) => {
          res.data.forEach((item) => {
            delete item.id
          })
          this.detailDataList = res.data
        })
      }
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach((key) => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {},
  methods: {
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          number: '',
          name: '',
          specification: '',
          unit: '',
          taxRate: '',
          taxes: '',
          count: '',
          price: '',
          amount: '',
          settleCount: '',
          settleAmount: '',
          description: '',
          createTime: ''
        }
      ]
    },
    delRow() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getDocDetail(id) {
      getMaterialContractSettleInfoDetail({
        materialContractSettleInfoId: id
      }).then((res) => {
        // const { lstAttachment } = res.data || {}
        // if (lstAttachment && lstAttachment.length > 0) {
        //   this.fileList = lstAttachment
        // }
        if (res.data.lstAttachment && res.data.lstAttachment.length > 0) {
          this.fileList = res.data.lstAttachment
        }
        if (res.data.lstMaterialContractSettleMaterial.length > 0) {
          this.detailDataList = res.data.lstMaterialContractSettleMaterial
        }
        this.form = res.data.materialContractSettleInfo
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          const params = {
            materialContractSettleInfo: {
              ...formData,
              materialContractInfoId: this.relateData.id,
              settleCount: Number(formData.settleCount),
              settleAmount: Number(formData.settleAmount),
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstMaterialContractSettleMaterial: this.detailDataList,
            lstAttachment: this.fileList
          }
          if (this.optType === 'edit') {
            params.materialContractSettleInfo.id = this.data.id
          } else {
            delete params.materialContractSettleInfo.id
          }
          const fn =
            this.optType === 'add'
              ? addMaterialContractSettleInfo
              : updateMaterialContractSettleInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    inputCount() {
      this.detailDataList.forEach((item, index) => {
        if (item.count && item.price) {
          item.amount =
            Number.parseFloat(item.count) * Number.parseFloat(item.price)
          item.amount = Number.parseFloat(item.amount).toFixed(2)
        } else {
          item.amount = ''
        }

        if (item.settleCount && item.price) {
          item.settleAmount =
            Number.parseFloat(item.settleCount) * Number.parseFloat(item.price)
          item.settleAmount = Number.parseFloat(item.settleAmount).toFixed(2)
        } else {
          item.settleAmount = ''
        }
      })
      this.$forceUpdate()
    },
    inputPrice() {
      this.detailDataList.forEach((item, index) => {
        if (item.count && item.price) {
          item.amount =
            Number.parseFloat(item.count) * Number.parseFloat(item.price)
          item.amount = Number.parseFloat(item.amount).toFixed(2)
        } else {
          item.amount = ''
        }
        if (item.settleCount && item.price) {
          item.settleAmount =
            Number.parseFloat(item.settleCount) * Number.parseFloat(item.price)
          item.settleAmount = Number.parseFloat(item.settleAmount).toFixed(2)
        } else {
          item.settleAmount = ''
        }
      })
      this.$forceUpdate()
    },
    inputSettleCount() {
      let sum = 0
      this.detailDataList.forEach((item, index) => {
        if (item.settleCount) {
          sum = sum + Number.parseFloat(item.settleCount)
        } else {
          this.form.settleCount = ''
        }

        if (item.settleCount && item.price) {
          item.settleAmount = Number.parseFloat(item.settleCount) * Number.parseFloat(item.price)
          item.settleAmount = Number.parseFloat(item.settleAmount).toFixed(2)
          this.inputSettleAmount()
        } else {
          item.settleAmount = ''
        }
      })
      this.form.settleCount = Number.parseFloat(sum).toFixed(2)
    },
    inputSettleAmount() {
      let sum = 0
      this.detailDataList.forEach((item, index) => {
        if (item.settleAmount) {
          sum = sum + Number.parseFloat(item.settleAmount)
        } else {
          this.form.settleAmount = ''
        }
      })
      this.form.settleAmount = Number.parseFloat(sum).toFixed(2)
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409eff;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
